<?php
/**
 * Created by PhpStorm.
 * User: yixuepai
 * Date: 2019/12/18
 * Time: 11:53
 */

class Wxchat
{
    private $appid = '';
    private $appsecret = '';
    private $openid = '';
    private $accesstoken = '';
    public function __construct($appid,$appsecret,$accesstoken='')
    {
        $this->appid        = $appid;
        $this->appsecret    = $appsecret;
        $this->accesstoken  = $accesstoken;
    }
    private function createNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    /**
     * 获取openid
     * @param $code         唯一code码
     * @param int $type     默认type = 0  type = 2 获取手机号时用
     * @return array
     */
    public function getopenid($code,$type=1){
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$this->appid."&secret=".$this->appsecret."&js_code=".$code."&grant_type=authorization_code";
        $res = json_decode(file_get_contents($url),true);
        if(isset($res['errcode'])){
           return array(
               'code'   => '10048',
               'message'=>'获取openid失败，请重试',
               'openid' => '',
               'sessionKey' => ''
           );
        }else {
            $openid = $res['openid'];
            return array(
                'code'      => '1',
                'openid'    => $openid,
                'sessionKey'    => $res['session_key'],
                'message'   => ''
            );
        }
    }
    /**
     * 获取accesstoken
     * @return mixed
     * @throws Exception
     */
    public function getaccesstoken(){
        // 如果是企业号用以下URL获取access_token
        // $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret";
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appid."&secret=".$this->appsecret;
        $res = json_decode(file_get_contents($url));
        $access_token = $res->access_token;
        $this->accesstoken = $access_token;
        return $access_token;
    }
    /**
     * 获取手机号
     * @param $sessionKey           获取手机号用到的sessionKey
     * @param $encryptedData        获取手机号的加密参数
     * @param $iv                   获取手机号的加密参数
     * @return bool
     */
    public function getphone($sessionKey,$encryptedData,$iv){
        $pc = new \wxBizDataCrypt($this->appid, $sessionKey);
        $errCode = $pc->decryptData($encryptedData, $iv, $data);
        if ($errCode == 0 && empty($data) === FALSE) {
            $d = json_decode($data, true);
            return array(
                'code'  => 1,
                'data'  => $d['phoneNumber']
            );
        } else {
            return array(
                'code'  => $errCode,
                'data'  => ''
            );
        }
    }

    /**
     * 生成短连接
     * @param $accessToken
     * @param $path
     * @param $page_title
     * @param $is_permanent
     * @return array
     * @throws Exception
     */
    public function createshortLink($accessToken,$path='',$page_title='',$is_permanent=false){
        $url = 'https://api.weixin.qq.com/wxa/genwxashortlink?access_token='.$accessToken;
        $data = json_encode(array(
            'page_url'          => $path,
            'page_title'        =>'商品',
            'is_permanent'      => $is_permanent
        ));
        $headers = array(
            'Content-Type: application/x-www-form-urlencoded'
        );
        $result = \Tools::curl($url,'POST',$data,$headers);
        $result = json_decode($result,true);
        if(isset($result['errcode']) && $result['errcode'] != 0){
            return array(
                'code'      => $result['errcode'],
                'message'   => $result['errmsg'],
                'data'      => ''
            );
        }else{
            return array(
                'code'      => $result['errcode'],
                'data'      => $result['link'],
                'message'   => $result['errmsg'],
            );
        }
    }
    /**
     * 生成小程序带参数二维码A
     */
    public function createqrcodea($accessToken,$path = '',$width = 430,$auto_color = false,$line_color = false,$is_hyaline = true){
        if(!$line_color){
            $line_color = json_decode('{"r":0,"g":0,"b":0}',true);
        }
        $url = 'https://api.weixin.qq.com/wxa/getwxacode?access_token='.$accessToken;
        $data = json_encode(array(
            'path'          => $path,
            'width'         => $width,
            'auto_color'    => $auto_color,
            'line_color'    => $line_color,
            'is_hyaline'    => $is_hyaline
        ));
        $headers = array(
            'Content-Type: application/x-www-form-urlencoded'
        );
        //POST参数
        $result = self::httpRequest($url,$data,"POST");
        if(isset($result['errcode']) && $result['errcode'] != 0){
            return array(
                'code'      => $result['errcode'],
                'message'   => $result['errmsg'],
                'data'      => ''
            );
        }else{
            return array(
                'code'      => 1,
                'data'      => $result,
                'message'   => ''
            );
        }
    }
    private static function httpRequest($url,$data='',$method='GET'){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL,$url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($curl, CURLOPT_USERAGENT,$_SERVER['HTTP_USER_AGENT']);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
        if($method=='POST')
        {
            curl_setopt($curl, CURLOPT_POST, 1);
            if ($data !='')
            {
                curl_setopt($curl, CURLOPT_POSTFIELDS,$data);
            }
        }

        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($curl);
        curl_close($curl);
        return $result;
  }
    /**
     * 生成小程序带参数二维码B
     */
    public function createqrcodeb($accessToken,$scene='',$page='page/index/index',$width = 430,$auto_color = false,$line_color = false,$is_hyaline = false){
        $url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$accessToken;
        if(!$line_color){
            $line_color = '{"r":0,"g":0,"b":0}';
        }
        $data = json_encode(array(
            'page'          => $page,
            'scene'         => $scene,
            'width'         => $width,
            'auto_color'    => $auto_color,
            'line_color'    => $line_color,
            'is_hyaline'    => $is_hyaline
        ));
        $res = \Tools::curl($url,'POST',$data);
        if(isset($res['errcode'])){
            return array(
                'code'      => $res['errcode'],
                'message'   => $res['errmsg'],
                'data'      => ''
            );
        }else{
            return array(
                'code'      => 1,
                'data'      => $res['buffer'],
                'message'   => $res['errmsg']
            );
        }
    }
    /**
     * 发送小程序模板消息
     * @return array|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function sendtmpldetail($openid,$template_id,$accessToken,$con=''){

        if(isset($accessToken) && empty($accessToken) === FALSE && empty($openid) === FALSE){
            $url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token='.$accessToken;
            $data = array(
                "thing9" => array(
                    "value" => $con
                ),
                "time16" => array(
                    "value" => \Tools::getDateTimeByTime(time(),'Y-m-d H:i')
                )
            );
            $result = \Tools::curl($url,'POST',json_encode(array(
                'touser'        => $openid,
                'page'          => 'pages/autolog/autolog',
                'template_id'   => $template_id,
                'data'          => $data
            )));
            $result = json_decode($result,true);
            return  $result;
        }else{
            return \Tools::returnMsg(false,array(
                'code'      => '60012',
                'message'   => '参数有误'
            ));
        }
    }
}
